package com.baize.cpdepus.controller;

import com.baize.cpdepus.common.R;
import com.baize.cpdepus.entity.Article;
import com.baize.cpdepus.service.ArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RequestMapping("/article")
@RestController
@Slf4j
@CrossOrigin  //跨域
@Api(value = "物品操作", tags = "物品操作接口")
public class ArticleController {
    @Autowired
    private ArticleService articleService;


    //物品的详细查询
    @GetMapping("getOne")
    @ApiOperation(value = "物品的详细查询")
    public R<Article> getOne(
            @ApiParam(value = "商品ID", required = true)
            Integer ID) {
        Article articleOne = articleService.getID(ID);
        return R.success(articleOne);
    }

    //    主要物品的查询  现为1到10查询，后改为点赞或查询次数最多查询 现写在controller中 后改为service中
    @GetMapping("homepageData")
    @ApiOperation(value = "主要物品的查询")
    public R<List<Article>> homepageData() {

        List<Article> random = articleService.getRandom();
        return R.success(random);
    }

    @GetMapping("getCategoryById")
    public R<List<Article>> getCategoryById(Integer categoryId) {
        return R.success(articleService.getCategoryAll(categoryId));
    }

    @GetMapping("nameSearch")
    public R<List<Article>> nameSearch(String name) {
        return R.success(articleService.getNameAll(name));
    }

    //    上架商品
    @PostMapping("add")
    @ApiOperation(value = "上架商品")
    public R<String> add(
            @ApiParam(value = "商品信息", required = true)
            Article article,
            @ApiParam(value = "图片", required = true)
            MultipartFile file) {
        try {
            articleService.addOne(article, file);
        } catch (IOException e) {
            log.info("上架商品出现问题");
            throw new RuntimeException(e);
        }
        return R.success("上架成功");
    }


    @PostMapping("remove")
    @ApiOperation(value = "下架商品")
    public R<String> remove(
            @ApiParam(value = "商品ID", required = true)
            Integer Id) {

        articleService.removeOne(Id);
        return R.success("下架成功");
    }
}
